import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;
import 'package:get/get.dart';

class WXUtil {
  final String wx_appid = 'wx74c3f1abaacda5dc';
  static final WXUtil instance = WXUtil._();

  factory WXUtil() {
    return instance;
  }
  WXUtil._() {
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        //微信授权
        var params = {"appid": wx_appid, "code": res.code, 'use_platform': 20};
        _login(code: res.code!, grantType: res.type);
      }
    });
  }
  Future<void> register() async {
    var res = await fluwx.registerWxApi(appId: wx_appid);
    Get.log('微信注册', isError: !res);
  }

  Future<bool> get isWxInstalled async {
    return fluwx.isWeChatInstalled;
  }

  void login() async {
    ///[scope] 应用授权作用域，如获取用户个人信息则填写 snsapi_userinfo
    ///[state] 用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止 csrf 攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加 session 进行校验

    var res =
        await fluwx.sendWeChatAuth(scope: 'snsapi_userinfo', state: 'topnet');
    Get.log(res ? 'wx_auth success' : 'wx_auth fail');
  }

  void _login({
    required String code,
    required int grantType,
  }) async {
    // HttpMan.instance.get(
    //   'https://api.weixin.qq.com/sns/oauth2/access_token',
    //   args: {
    //     'appid': key_wx,
    //     'secret': 'secret',
    //     'code': code,
    //     'grant_type': grantType,
    //   },
    //   success: (data) {
    //     Get.log(data.toString());
    //   },
    //   fail: (code, msg) {
    //     EasyLoading.showToast(msg);
    //   },
    // );
  }

  Future<bool> share(fluwx.WeChatShareBaseModel md) async {
    return fluwx.shareToWeChat(md);
  }
}
